import HeadPrefab from "../../component/HeadPrefab";
import DateUtil from "../../engine/DateUtil";
import { Logger } from "../../engine/Logger";
import { SpriteFrameComponent } from "../../engine/SpriteFrameComponent";
import UIManager from "../../engine/UIManager";
import ViewBase from "../../engine/ViewBase";
import GameController from "../../GameController";
import { SocketClient } from "../../net/SocketClient";
import { GameConfig } from "../config/GameConfig";
import { RoomConfig } from "../config/RoomConfig";
import { RoomJinbiConfig } from "../config/RoomJinbiConfig";
import { ViewConfig } from "../config/ViewConfig";
import { RoomModel } from "../model/RoomModel";
import { RoomPlayer } from "../model/RoomPlayer";
import { RoomTemplateModel } from "../model/RoomTemplateModel";
import { UIHelper } from "../util/UIHelper";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ViewZiyouDesk extends ViewBase {

    private config: RoomJinbiConfig
    private deskItemNode: cc.Node;
    private isShowLeft: boolean = true
    private showGameType: number = 0
    private lastGetTime: number = 0
    private leftNode: cc.Node

    public onInitChild(config: RoomJinbiConfig): void {
        this.config = config
    }

    onEnable(): void {
        super.onEnable()
        this.leftNode = this.findChild(this.node, "leftNode")
        this.deskItemNode = this.findChild(this.node, "scrollView/view/content/deskItemNode")
        let btnBack: cc.Node = this.findChild(this.node, "btnBack")
        UIHelper.onAddEvent(btnBack, () => {
            // GameController.instance.gotoHall(true)
            UIManager.instance.showView(ViewConfig.viewConfig.ViewZiyouRoom, () => {
                this.closeView()
            })
        })

        this.refreshLeftNode()
        this.refreshDesk()
    }


    protected update(dt: number): void {
        this.getRoom()
    }

    private getRoom() {
        if (DateUtil.now() - this.lastGetTime >= 1000) {
            this.lastGetTime = DateUtil.now()
            SocketClient.req_ziyou_room(this.config.level, () => {
                this.refreshDesk()
            })
        }
    }

    private refreshLeftNode() {
        let leftNode: cc.Node = this.leftNode
        for (let i = 0; i < 7; i++) {
            let btnGame: cc.Node = leftNode.getChildByName("btnGame" + i)
            btnGame.active = this.isShowLeft
            if (i == this.showGameType) {
                btnGame.getComponent(cc.Sprite).spriteFrame = btnGame.getComponent(SpriteFrameComponent).spriteFrameList[1]
            } else {
                btnGame.getComponent(cc.Sprite).spriteFrame = btnGame.getComponent(SpriteFrameComponent).spriteFrameList[0]
            }
            UIHelper.onAddEvent(btnGame, () => {
                this.showGameType = i
                this.refreshLeftNode();
                this.refreshDesk()
            })
        }
        let btnRight: cc.Node = this.findChild(leftNode, "btnRight")
        btnRight.active = !this.isShowLeft;
        UIHelper.onAddEvent(btnRight, () => {
            this.isShowLeft = true;
            this.leftNode.x = -547
            this.refreshLeftNode()
        })
        let btnLeft: cc.Node = this.findChild(leftNode, "btnLeft")
        btnLeft.active = this.isShowLeft;
        UIHelper.onAddEvent(btnLeft, () => {
            this.isShowLeft = false
            this.leftNode.x = -728
            this.refreshLeftNode()
        })
    }

    private refreshDesk() {
        this.hideAllChildren(this.deskItemNode.parent)
        let allRoomList: Array<RoomModel> = RoomModel.ziyouRoomList;
        let noFullRoomList: Array<RoomModel> = []
        let fullRoomList: Array<RoomModel> = []
        for (let i = 0; i < allRoomList.length; i++) {
            let room: RoomModel = allRoomList[i]
            if (this.showGameType == 0 || this.showGameType == room.gameType) {
                if (room.getPlayerNum() >= room.conf.renshu) {
                    fullRoomList.push(room)
                } else {
                    noFullRoomList.push(room)
                }
            }

        }
        let templateList: Array<RoomTemplateModel> = RoomTemplateModel.getZiyouListByGameType(this.showGameType)

        let allList: Array<RoomModel | RoomTemplateModel> = []
        allList = allList.concat(noFullRoomList)
        allList = allList.concat(templateList)
        allList = allList.concat(fullRoomList)
        Logger.log("refreshDesk=====", allList)

        for (let i = 0; i < allList.length; i++) {
            let model: RoomTemplateModel | RoomModel = allList[i]
            let item: cc.Node = this.deskItemNode.parent.children[i]
            if (!item) {
                this.scheduleOnce(() => {
                    this.initOneDesk(model, i)
                }, 0.02 * i)
            } else {
                item.active = true;
                this.initOneDesk(model, i)
            }
        }
    }

    private initOneDesk(model: RoomTemplateModel | RoomModel, i: number) {
        let item: cc.Node = this.deskItemNode.parent.children[i]
        if (!item) {
            item = cc.instantiate(this.deskItemNode)
            item.parent = this.deskItemNode.parent;
        }
        item.active = true;
        let lbName: cc.Label = this.getChild(item, "lbName", cc.Label)
        if (model.conf["name"] && model.conf["name"] != "") {
            lbName.string = model.conf["name"]
        } else {
            lbName.string = ""
        }
        if (model instanceof RoomTemplateModel) {
            if (model.name) {
                lbName.string = model.name;
            } else {
                lbName.string = ""
            }
        }
        UIHelper.onAddEvent(item, () => {
            Logger.log("点击桌子==", model)
            if (model instanceof RoomModel) {
                SocketClient.req_join_room(model.room_id)
            } else {
                model.conf["name"] = model.name
                SocketClient.req_create_room(model.conf, RoomConfig.Room_Type.Ziyou)
            }
        })

        let desk_poker: cc.Node = this.findChild(item, "desk_poker")
        let desk_mj: cc.Node = this.findChild(item, "desk_mj")
        if (model.gameType == GameConfig.Game_Type.ddz || model.gameType == GameConfig.Game_Type.jianziding
            || model.gameType == GameConfig.Game_Type.paodekuai) {
            desk_poker.active = true
            desk_mj.active = false
            this.refreshDeskOne(desk_poker, model)
        }
        else {
            desk_poker.active = false
            desk_mj.active = true
            this.refreshDeskOne(desk_mj, model)
        }

    }

      // 红   斗地主         蓝  跑得快   绿  尖子
    // 麻将         蓝黄骅     绿沧县   红二人
    private refreshDeskOne(deskNode: cc.Node, model: RoomTemplateModel | RoomModel) {
        let renshu: number = model.conf["renshu"]
        this.hideAllChildren(deskNode)
        let deskBg:cc.Node = this.findChild(deskNode, "deskBg")
        deskBg.active = true
        let txtGameName: cc.Label = this.getChild(deskNode, "txtGameName", cc.Label)
        txtGameName.node.active = true
        txtGameName.string = "" + renshu + "人" + GameConfig.GameNameList[model.gameType]
        let txtJushu: cc.Label = this.getChild(deskNode, "txtJushu", cc.Label)
        txtJushu.node.active = true
        txtJushu.string = ""
        let blueDesk: cc.Node = this.findChild(deskNode, "blueDesk")
        let redDesk: cc.Node = this.findChild(deskNode, "redDesk")
        if (model.gameType == GameConfig.Game_Type.ddz || model.gameType == GameConfig.Game_Type.dazhonger_mj) {
            redDesk.active = true
        }
        else if (model.gameType == GameConfig.Game_Type.paodekuai || model.gameType == GameConfig.Game_Type.huanghua_mj) {
            blueDesk.active = true
        }

        let childName: string = "chairNode" + renshu;
        let chairNode: cc.Node = deskNode.getChildByName(childName)
        chairNode.active = true;
        for (let i = 0; i < renshu; i++) {
            let btnJoinDesk: cc.Node = this.findChild(chairNode, "btnJoinDesk" + i)
            btnJoinDesk.active = false
            let head: HeadPrefab = this.getChild(chairNode, "head" + i, HeadPrefab)
            head.node.active = false
        }
        if (model instanceof RoomModel) {
            if (model.num_of_turns >= 1) {
                txtJushu.string = "已开局" + model.num_of_turns + "/" + model.conf.jushu;
            } else {
                txtJushu.string = "等待中"
            }
            for (let i = 0; i < renshu; i++) {
                let btnJoinDesk: cc.Node = this.findChild(chairNode, "btnJoinDesk" + i)
                let head: HeadPrefab = this.getChild(chairNode, "head" + i, HeadPrefab)
                if (model.num_of_turns >= 1) {
                    btnJoinDesk.active = false
                } else {
                    btnJoinDesk.active = true
                }
                let player: RoomPlayer = model.playerList[i]
                if (player) {
                    head.node.active = true
                    head.setHead(player.headimg, player.lv)
                    let txtName: cc.Label = this.getChild(head.node, "txtName", cc.Label)
                    txtName.string = player.nick_name;
                }
            }
        }

    }
  
}
